package com.mall.service;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mall.dao.mapper.SeckillMapper;
import com.mall.model.Cart;
import com.mall.model.CommDetailed;
import com.mall.model.Commodity;
import com.mall.model.Seckill;
import com.mall.model.SeckillExample;
import com.mall.model.SeckillExample.Criteria;

@Service
public class SeckillService {
	@Autowired
	private SeckillMapper seckillMapper;
	@Autowired
	private CommodityService commodityService;
	@Autowired
	private CommDetailedService commDetailedService;
	@Autowired
	private CartService cartService;
	public static String path;

	/**
	 * 购买成功加入购物车
	 * 
	 * @param snum
	 * @throws Exception
	 *
	 * @dagewang 2017年9月27日
	 */
	public Integer createOrder(Integer userid, Integer id, int snum) throws Exception {
		Seckill s = seckillMapper.selectByPrimaryKey(id);
		Commodity commById = commodityService.getCommById(s.getCommid());
		if (commById == null) {
			return null;
		}
		if (snum == 1) {
			s.setState(1);
			BufferedWriter bw = null;
			try {
				bw = new BufferedWriter(
						new OutputStreamWriter(new FileOutputStream(path + "seckill/js/" + id + ".js", true), "UTF-8"));
				bw.write("function changesub(){var div=$('#killStart');div.html('已经售罄!');div.css({'cursor':"
						+ "'not-allowed','background':'#EEDFCC','color':'#BEBEBE','border-color':'#EED8AE'});div.attr('href','#');div.attr('href','#')}");
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			} finally {
				bw.close();
			}
		}
		s.setCountnum(s.getCountnum() - 1);
		seckillMapper.updateByPrimaryKeySelective(s);
		Cart c = new Cart();
		c.setCdate(new Date());
		c.setClassname("秒杀商品");
		c.setCommid(s.getCommid());
		c.setPrice(s.getPrice());
		c.setCommname(commById.getTitle());
		c.setUserid(userid);
		c.setImg(commById.getTitleimg());
		c.setCommnum(1);
		c.setStock(1);
		c.setSeckill(id);
		int save = cartService.save(c);
		return save;
	}

	public SeckillMapper getSeckillMapper() {
		return seckillMapper;
	}

	public void setSeckillMapper(SeckillMapper seckillMapper) {
		this.seckillMapper = seckillMapper;
	}

	/**
	 * 创建秒杀
	 *
	 * @dagewang 2017年9月29日
	 */
	public Integer save(Double price, String sdate, String edate, Integer id, Integer num, String path)
			throws Exception {
		// 判断是否还有未完成的同一个商品的秒杀
		SeckillExample ex = new SeckillExample();
		Criteria createCriteria = ex.createCriteria();
		createCriteria.andStateEqualTo(0);
		createCriteria.andCommidEqualTo(id);
		List<Seckill> selectByExample = seckillMapper.selectByExample(ex);
		if (selectByExample.size() != 0) {
			return null;
		}
		Commodity commById = commodityService.getCommById(id);
		if (commById == null) {
			return null;
		}
		// 如果没有才创建
		Seckill s = new Seckill();
		s.setCdate(new Date());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date date1 = null;
		Date date2 = null;
		date1 = sdf.parse(sdate);
		date2 = sdf.parse(edate);
		s.setTitle(commById.getTitle());
		s.setImg(commById.getTitleimg());
		s.setCountnum(num);
		s.setSdate(date1);
		s.setEdate(date2);
		s.setCommid(id);
		s.setState(0);
		s.setPrice(price);
		s.setDeletejs(0);
		int insert = seckillMapper.insert(s);
		Integer result = null;
		if (insert == 1) {
			List<Seckill> seckilist = seckillMapper.selectByExample(ex);
			if (seckilist.size() > 0) {
				Seckill seckill = seckilist.get(0);
				result = seckill.getId();
				this.createView(result, path, id);
				this.createJs(commById, result, path, price, num, date1);
			}
		}
		return result;
	}

	/**
	 * 生成js
	 *
	 * @dagewang 2017年9月27日
	 */
	public void createJs(Commodity comm, Integer id, String path, Double price, Integer num, Date date)
			throws Exception {
		String img = "";
		String title = "";
		Double oldprice = null;
		if (comm != null) {
			img = comm.getTitleimg();
			title = comm.getTitle();
			oldprice = comm.getPrice();
		}

		BufferedWriter bw = new BufferedWriter(
				new OutputStreamWriter(new FileOutputStream(path + "js/" + id + ".js"), "UTF-8"));
		String str = "$(document).ready(function(){" + "$('#img').attr('src','/mall/file/img/" + img + "');"
				+ "$('#price').html('" + price + "元');" + "$('#title').html('" + title + "');" + "$('#oldprice').html('"
				+ oldprice + "元');" + "$('#num').html('" + num + "');$('#para').html('');" + "$('#killid').val('" + id
				+ "');" + "$('#sdate').val('" + date.getTime() + "');});";
		bw.write(str);
		bw.flush();
		bw.close();
	}

	/**
	 * 生成视图
	 *
	 * @dagewang 2017年9月27日
	 */
	public void createView(Integer id, String path, Integer commid) throws Exception {
		BufferedReader br = null;
		BufferedWriter bw = null;
		CommDetailed cd = commDetailedService.get(commid);
		String content = null;
		if (cd != null) {
			content = cd.getContent();
		}
		try {
			// 建立高效读取对象
			br = new BufferedReader(new InputStreamReader(new FileInputStream(path + "jsp/seckill.jsp"), "UTF-8"));
			// 建立高效写入对象
			bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path + "jsp/" + id + ".jsp"), "UTF-8"));
			String str = null;
			// 进行读取
			while ((str = br.readLine()) != null) {
				if (str.equals("<script id='js' src=''></script>")) {
					str = "<script id='js' src='${pageContext.request.contextPath}/seckill/js/" + id
							+ ".js?1=1'></script>";
				}
				if (str.equals("thiscontent")) {
					str = content;
				}
				// 进行写入
				bw.write(str);
				bw.newLine();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bw != null && br != null) {
				try {
					// 关闭资源，要先开后关，后开先关
					bw.close();
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}
	}

	/**
	 * 秒杀商品集合
	 * 
	 * @param page
	 *
	 * @dagewang 2017年9月29日
	 */
	public List<Seckill> list(Integer page) {
		SeckillExample ex = new SeckillExample();
		RowBounds r = new RowBounds(page * 2, 2);
		ex.setOrderByClause("sdate asc");
		ex.createCriteria().andStateEqualTo(0);
		List<Seckill> selectByExample = seckillMapper.selectByExampleWithRowbounds(ex, r);
		return selectByExample;
	}

	public CommodityService getCommodityService() {
		return commodityService;
	}

	public void setCommodityService(CommodityService commodityService) {
		this.commodityService = commodityService;
	}

	public CommDetailedService getCommDetailedService() {
		return commDetailedService;
	}

	public void setCommDetailedService(CommDetailedService commDetailedService) {
		this.commDetailedService = commDetailedService;
	}

	public CartService getCartService() {
		return cartService;
	}

	public void setCartService(CartService cartService) {
		this.cartService = cartService;
	}

	/**
	 * 根据id取
	 *
	 * @dagewang 2017年9月29日
	 */
	public Seckill get(Integer seckill) {
		Seckill selectByPrimaryKey = seckillMapper.selectByPrimaryKey(seckill);
		return selectByPrimaryKey;
	}

	/**
	 * 获取集合,只获取id,sdate,edate,countnum
	 *
	 * @dagewang 2017年9月30日
	 */
	public List<com.mall.model.Seckill> listAndUpdate() {
		SeckillExample ex = new SeckillExample();
		ex.createCriteria().andStateEqualTo(0);
		List<Seckill> selectByExample = null;
		try {
			selectByExample = seckillMapper.selectByExampleOptimization(ex);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return selectByExample;
	}

	/**
	 * 更新已过期的秒杀为不可用,删除过期文件
	 *
	 * @dagewang 2017年9月30日
	 */
	public void update() {
		List<Seckill> s = seckillMapper.selectByStateOrEdate();
		List<Integer> u = new ArrayList<Integer>();
		List<Integer> all = new ArrayList<Integer>();
		String path = this.getClass().getResource("/").getPath();
		int indexOf = path.indexOf("WEB-INF");
		String substring = path.substring(1, indexOf);
		SeckillService.path = substring;
		if (s != null && s.size() != 0) {
			for (Seckill kill : s) {
				Integer killid = kill.getId();
				File js = new File(substring + "seckill/js/" + killid + ".js");
				File jsp = new File(substring + "seckill/jsp/" + killid + ".jsp");
				js.delete();
				jsp.delete();
				if (kill.getState() == 0) {
					kill.setState(1);
					u.add(killid);
				}
				all.add(killid);
			}
			//更新秒杀状态和删除状态
			if (u.size() != 0) {
				SeckillExample ex = new SeckillExample();
				ex.createCriteria().andIdIn(u);
				Seckill seckill = new Seckill();
				seckill.setState(1);
				seckillMapper.updateByExampleSelective(seckill, ex);
			}
			if(all.size()!=0){
				SeckillExample ex2 = new SeckillExample();
				ex2.createCriteria().andIdIn(all);
				Seckill seckill = new Seckill();
				seckill.setDeletejs(1);
				seckillMapper.updateByExampleSelective(seckill, ex2);
			}
			
		}
	}

	public List<Seckill> syslist(Integer page) {
		SeckillExample ex = new SeckillExample();
		RowBounds r = new RowBounds(page * 6, 6);
		ex.setOrderByClause("sdate asc");
		ex.createCriteria().andStateNotEqualTo(1);
		List<Seckill> selectByExample = seckillMapper.selectByExampleWithRowbounds(ex, r);
		return selectByExample;
	}
	/**
	 * 更新详细信息
	 *
	 *@dagewang 2017年10月9日
	 */
	public int updateData(Seckill seckill) {
		int updateByPrimaryKeySelective = seckillMapper.updateByPrimaryKeySelective(seckill);
		return updateByPrimaryKeySelective;
	}


}
